<!-- 创建销售单 -->
<template>
  <view>
    <form @submit="onFormSubmit">
      <view class="form-container">
        <view class="eform-item">
          <view class="form-label">店铺</view>
          <view
            class="form-value"
            @click="goPage('/pagesB/systemSet/ShopList?source=1')"
          >
            <text class="input-pl" v-if="!add_form.shopName">请选择</text>
            <text v-else>{{ add_form.shopName }}</text>
            <i class="ibonfont ibonjinru icon-jinru"></i>
          </view>
        </view>
        <view class="eform-item">
          <view class="form-label">客户</view>
          <view
            class="form-value"
            @click="goPage('/pagesT/customer/selCustomer')"
          >
            <text class="input-pl" v-if="!add_form.customerName">请选择</text>
            <text v-else>{{ add_form.customerName }}</text>
            <i class="ibonfont ibonjinru icon-jinru"></i>
          </view>
        </view>
        <!-- <view class="eform-item">
          <view class="form-label">小票打印</view>
          <view class="form-value">
            <switch
              :checked="add_form.isEnablePrint === 5"
              @change="isEnablePrintChange"
            />
          </view>
        </view> -->
        <view class="eform-item" v-if="address_list.length">
          <view class="form-label">收货人</view>
          <view class="form-value">
            <StatusSel
              @pickerChange="pickerAddressChange"
              :options="address_list"
            >
              <text class="input-pl" v-if="!receiveName">请选择</text>
              <text v-else>{{ receiveName }}</text>
              <i class="ibonfont ibonjinru icon-jinru"></i>
            </StatusSel>
          </view>
        </view>
        <view class="eform-item" v-if="address_list.length">
          <view class="form-label">收货电话</view>
          <view class="form-value">{{ receivePhone }}</view>
        </view>
        <view class="eform-item" v-if="address_list.length">
          <view class="form-label">收货地址</view>
          <view class="form-value">{{ receiveAddress }}</view>
        </view>
        <view class="goods-ul b20">
          <view
            class="goods-item"
            v-for="(item, index) in saleOrderGoods"
            :key="index"
          >
            <view class="clearfix goods-goods">
              <view @click="deleteRowGoods(index)" class="delGoods float_left"
                ><i class="ibonfont ibondelete"></i
              ></view>
              <view class="float_left goods-img"
                ><image :src="item.goodsImages" mode="aspectFill"></image
              ></view>
              <view class="float_left goods-cont-right">
                <view class="goods-tit">{{ item.title }}</view>
                <view class="goods-info clearfix">
                  <view class="float_left">
                    <text class="gi-label">编号：</text>
                    <text class="gi-value">{{ item.code }}</text>
                  </view>
                </view>
                <view class="goods-info clearfix">
                  <view class="float_left" style="width: 320rpx">
                    <text class="gi-label">规格：</text>
                    <text class="gi-value">
                      {{ item.unitName }}
                      <block
                        v-for="(itemSp, indexSp) in item.specGroup"
                        :key="indexSp"
                        >_{{ itemSp.specValueName }}</block
                      >
                    </text>
                  </view>
                </view>
                <view class="goods-info clearfix">
                  <view class="float_left" style="width: 320rpx">
                    <text class="gi-label">可用库存：</text>
                    <text class="gi-value">{{ item.inventoryNum - 0 }}</text>
                  </view>
                  <view class="error-color">金额：¥ {{ item.totalMoney }}</view>
                </view>
                <view class="goods-info clearfix">
                  <view class="float_left">
                    <text class="gi-label">数量：</text>
                    <input
                      type="digit"
                      @confirm="updateBuyNum(index)"
                      @blur="updateBuyNum(index)"
                      v-model="item.buyNum"
                      class="buyNum-input"
                    />
                  </view>
                  <view class="error-color">
                    ¥
                    <input
                      type="digit"
                      @confirm="updatePrice(index)"
                      @blur="updatePrice(index)"
                      v-model="item.salePrice"
                      class="buyNum-input"
                    />
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="form-item form-pa20 clearfix">
          <view class="float_left form-label">
            订单总额
            <text class="icon-requird">*</text>
          </view>
          <view class="form-value">{{ orderAmount }}</view>
        </view>
        <view class="form-item form-pa20 add-form-item" @click="selGoods">
          <text class="ibonfont ibonxinzeng"></text>
          <text>新增商品</text>
        </view>
        <view class="form-up b20 clearfix">
          <view class="form-label">备注</view>
          <view class="form-value"
            ><input
              type="text"
              v-model="add_form.remark"
              placeholder-class="input-pl"
              placeholder="请输入"
          /></view>
        </view>
      </view>
      <view class="fixed-bottom">
        <button class="sub-btn" form-type="submit">保存</button>
      </view>
    </form>
  </view>
</template>

<script>
import StatusSel from "@/components/StatusSel.vue";
export default {
  components: {
    StatusSel,
  },
  data() {
    return {
      receiveName: "", // 收货人
      receivePhone: "", //收货电话
      receiveAddress: "", //收货地址
      saleOrderGoods: [],
      address_list: [], //客户收货地址列表
      add_form: {
        isEnablePrint: 5,
        shopName: "", //所属商铺name
        shopId: "", //所属商铺id
        totalMoney: 0,
        payAmount: 0,
        customerId: 0,
        userCenterId: 0,
        customerName: "",
        customerType: 0,
        receiveAddressId: "",
        source: 4,
        deliveryType: 2,
        remark: "",
        goodsData: {
          totalMoney: "",
          payMoney: "",
          preferential: "",
          checkNum: "",
          cartNum: "",
          goodsData: [],
        },
      },
      CustomerSel: "",
      userCenterId: "",
      goodsData: "",
      shopSel: "",
      // 用于接收选择页面返回的数据
      shopData: null,
      customerData: null,
      rules: {
        shopName: [
          {
            required: true,
            message: "请选择所属商铺",
          },
        ],
        customerName: [
          {
            required: true,
            message: "请选择购买客户",
          },
        ],
        receiveAddressId: [
          {
            required: true,
            message: "请选择收货人",
          },
        ],
      },
    };
  },
  onLoad(options) {
    // 获取店铺列表
    this.getAllShop();
    // 表单验证
    this.$nextTick(() => {
      this.$refs.form.setRules(this.rules);
    });
  },
  watch: {
    CustomerSel(val) {
      this.getAllShippingAddress(val.id);
      this.add_form.customerId = val.id;
      this.saleOrderGoods = [];
      this.add_form.goodsData = [];
    },
  },
  computed: {
    orderAmount() {
      if (!this.saleOrderGoods.length) {
        return 0;
      } else if (this.saleOrderGoods.length === 1) {
        return this.saleOrderGoods[0].totalMoney;
      } else {
        let sum = 0;
        this.saleOrderGoods.forEach((item) => {
          sum = this.$NP.plus(sum, Number(item.totalMoney) || 0);
        });
        return sum;
      }
    },
  },
  onShow() {
    // 处理店铺选择返回的数据
    if (this.shopData) {
      this.add_form.shopId = this.shopData.id;
      this.add_form.shopName = this.shopData.name;
      this.shopSel = this.shopData;
      this.shopData = null; // 清空数据避免重复处理
    }
    // 处理客户选择返回的数据
    if (this.customerData) {
      this.add_form.customerName = this.customerData.name;
      this.userCenterId = this.customerData.userCenterId;
      this.add_form.customerId = this.customerData.id;
      this.CustomerSel = this.customerData;
      this.customerData = null; // 清空数据避免重复处理
    }
    // 兼容旧的变量名
    if (this.shopSel && !this.shopData) {
      this.add_form.shopId = this.shopSel.id;
      this.add_form.shopName = this.shopSel.name;
    }
    // 选择商品
    if (this.goodsData) {
      const goodsList = this.goodsData.map((item) => {
        return {
          unitName: item.unitName,
          skuId: item.skuId,
          goodsId: item.id,
          buyNum: item.selNum,
          inventoryNum: item.inventory, // 不用传参
          totalMoney: this.$NP.times(
            Number(item.selNum),
            Number(item.salePrice)
          ),
          goodsName: item.title, // 商品名称
          shopId: item.shopId,
          shopName: item.shopName, // 店铺名称
          originPrice: item.originPrice,
          salePrice: item.salePrice,
          goodsBasicId: item.basicGoodsId, // 商品基础资料ID
          code: item.code,
          conversion: item.conversion,
          categoryPath: item.categoryPath,
          brandId: item.brandId,
          warehouseId: item.warehouseId,
          goodsImages: item.images[0], // 不用传参
          specGroup: item.specGroup, // 不用传参
        };
      });
      if (!this.saleOrderGoods.length) {
        this.saleOrderGoods = goodsList;
      } else {
        this.saleOrderGoods = this.$utils.unique(
          this.saleOrderGoods.concat(goodsList),
          ["goodsId", "skuId"]
        );
      }
    }
    // 兼容旧的客户选择逻辑
    if (this.CustomerSel && !this.customerData) {
      this.add_form.customerName = this.CustomerSel.name;
      this.userCenterId = this.CustomerSel.userCenterId;
      this.add_form.customerId = this.CustomerSel.id;
    }
  },
  methods: {
    isEnablePrintChange(e) {
      this.add_form.isEnablePrint = e.detail.value ? 5 : 4;
    },
    // 扫描
    handelScanGoods() {
      if (!this.userCenterId) {
        this.$u.toast("请选择客户");
        return;
      }
      // 调起条码扫描
      uni.scanCode({
        scanType: ["barCode"],
        success: (res) => {
          if (res.result) {
            this.getGoodsByBarCode(res.result);
          } else {
            this.$u.toast("没有找到对应商品");
          }
        },
      });
    },
    //根据条码获取商品
    async getGoodsByBarCode(barCode) {
      try {
        const response = await this.$u.api.getGoodsByBarCode({
          barCode: barCode,
        });
        const data = response.data;
        const nowSkuData = data.detail.specMultiple.find(
          (item) => item.id === data.skuId
        );
        const buyNum = nowSkuData.inventory > 0 ? 1 : 0;
        const detail = {
          unitName: nowSkuData.unitName,
          skuId: nowSkuData.id,
          goodsId: data.detail.id,
          buyNum: buyNum,
          inventoryNum: nowSkuData.inventory, // 不用传参
          totalMoney: this.$NP.times(buyNum, nowSkuData.salePrice),
          title: data.detail.title, // 商品名称
          shopId: data.detail.shopId,
          shopName: data.detail.shopName, // 店铺名称
          originPrice: nowSkuData.originPrice,
          salePrice: nowSkuData.salePrice,
          goodsBasicId: data.detail.basicGoodsId, // 商品基础资料ID
          code: data.detail.code,
          conversion: nowSkuData.conversion,
          categoryPath: data.detail.categoryPath,
          brandId: data.detail.brandId,
          warehouseId: data.detail.warehouseId,
          goodsImages: data.detail.images[0], // 不用传参
          specGroup: nowSkuData.specGroup, // 不用传参
        };
        this.saleOrderGoods.push(detail);
        this.saleOrderGoods = this.$utils.unique(this.saleOrderGoods, [
          "goodsId",
          "skuId",
        ]);
      } catch (error) {
        console.error("获取商品信息失败:", error);
        this.$u.toast("获取商品信息失败");
      }
    },
    //  获取店铺列表
    async getAllShop() {
      try {
        const response = await this.$u.api.getAllShop({
          page: 1,
          pageSize: 2,
        });
        const data = response.data || [];
        if (data.length) {
          this.add_form.shopId = data[0].id;
          this.add_form.shopName = data[0].name;
        }
      } catch (error) {
        console.error("获取店铺列表失败:", error);
      }
    },
    selGoods() {
      if (!this.userCenterId) {
        this.$u.toast("请选择客户");
        return;
      }
      this.goPage(
        `/pagesT/goods/selGoods?isBase=4&userCenterId=${this.userCenterId}&shopId=${this.add_form.shopId}`
      );
    },
    // 移出购物车
    async deleteRowGoods(index) {
      this.saleOrderGoods.splice(index, 1);
    },
    // 修改数量
    async updateBuyNum(index) {
      const target = this.$utils.deepClone(this.saleOrderGoods);
      console.log(213, target[index].buyNum, target[index].inventoryNum);
      if (target[index].buyNum > target[index].inventoryNum - 0) {
        this.$u.toast("库存不足");
        target[index].buyNum = 0;
      } else {
        target[index] = {
          ...target[index],
          totalMoney: this.$NP.times(
            target[index].salePrice,
            target[index].buyNum
          ),
        };
      }
      this.saleOrderGoods = target;
    },
    // 修改商品单价
    async updatePrice(index) {
      const target = this.$utils.deepClone(this.saleOrderGoods);
      target[index] = {
        ...target[index],
        totalMoney: this.$NP.times(
          target[index].salePrice,
          target[index].buyNum
        ),
      };
      this.saleOrderGoods = target;
    },
    async submitData() {
      this.$refs.form.validate(async (res) => {
        if (res) {
          if (!this.saleOrderGoods.length) {
            this.$u.toast("请选择商品");
            return;
          }
          const issub = this.saleOrderGoods.every((item) => {
            return item.buyNum;
          });
          if (!issub) {
            this.$u.toast("请输入数量");
            return;
          }
          let subGoodsArr = [];
          this.$utils.deepClone(this.saleOrderGoods).forEach((item) => {
            if (item.goodsId) {
              delete item.inventoryNum;
              delete item.specGroup;
              delete item.goodsImages;
              subGoodsArr.push(item);
            }
          });
          if (!subGoodsArr.length) {
            this.$message({
              type: "warning",
              message: "请选择商品",
            });
            return;
          }
          const addForm = this.$utils.deepClone(this.add_form);
          delete addForm.shopName;
          delete addForm.shopId;
          const params = {
            ...addForm,
            totalMoney: this.orderAmount,
            payAmount: this.orderAmount,
            goodsData: subGoodsArr,
          };
          uni.showLoading();
          try {
            const response = await this.$u.api.addSalesOrder(
              this.userCenterId,
              params
            );
            this.$u.toast("提交成功");
            this.goPage(`/pagesB/order/SaleOrderList`, "redirectTo");
          } catch (error) {
            console.error("提交订单失败:", error);
            this.$u.toast("提交订单失败");
          }
          uni.hideLoading();
        }
      });
    },
    // 获取客户收货地址列表
    async getAllShippingAddress(id) {
      try {
        const response = await this.$u.api.getAllShippingAddress(id);
        const data = response.data || [];
        this.address_list = data.map((item) => {
          return {
            ...item,
            label: item.name,
            value: item.id,
            area: item.area,
            mobile: item.mobile,
          };
        });
        if (this.address_list.length > 0) {
          this.receiveName = this.address_list[0].label;
          this.add_form.receiveAddressId = this.address_list[0].value;
          this.receivePhone = this.address_list[0].mobile;
          this.receiveAddress =
            this.address_list[0].area.provinceName +
            " " +
            this.address_list[0].area.cityName +
            " " +
            this.address_list[0].area.districtName +
            " " +
            this.address_list[0].area.address;
        }
      } catch (error) {
        console.error("获取收货地址失败:", error);
      }
    },
    // 选择收货地址
    pickerAddressChange(row) {
      this.receiveName = row.label;
      this.receivePhone = row.mobile;
      this.receiveAddress =
        row.area.provinceName +
        " " +
        row.area.cityName +
        " " +
        row.area.districtName +
        " " +
        row.area.address;
      this.add_form.receiveAddressId = row.value;
    },
    onFormSubmit(e) {
      // 基础form提交事件，直接调用原有submitData逻辑
      this.submitData();
    },
  },
};
</script>

<style lang="scss">
/* 页面整体背景 */
page {
  background: #f8f8f8;
}

/* 表单容器 */
.form-container {
  background: #fff;
  margin: 20upx;
  border-radius: 16upx;
  box-shadow: 0 2upx 16upx rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

/* 表单项样式 */
.eform-item {
  padding: 20upx 24upx;
  border-bottom: 1upx solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }

  .form-label {
    color: #333;
    font-weight: 500;
    font-size: 28upx;
  }

  .form-input {
    padding: 14upx 18upx;
    border: 1upx solid #e0e0e0;
    border-radius: 8upx;
    background: #f8f8f8;
    font-size: 28upx;
    transition: all 0.3s;

    &:focus {
      border-color: #fb5904;
      background: #fff;
      box-shadow: 0 0 0 2upx rgba(251, 89, 4, 0.1);
    }
  }

  .form-picker {
    padding: 14upx 18upx;
    border: 1upx solid #e0e0e0;
    border-radius: 8upx;
    background: #f8f8f8;
    font-size: 28upx;
    color: #333;
    transition: all 0.3s;

    &:active {
      background: #fff;
      border-color: #fb5904;
    }
  }
}

/* 商品列表样式 */
.goods-ul {
  margin: 20upx 0 0 0;
  background: #fff;
  border-radius: 14upx;
  box-shadow: 0 2upx 10upx rgba(0, 0, 0, 0.04);
  overflow: hidden;
}

.goods-item {
  border-bottom: 1upx solid #f0f0f0;
  padding: 18upx 18upx 18upx 18upx;
  background: #fff;
  display: flex;
  align-items: flex-start;
  transition: all 0.3s;

  &:last-child {
    border-bottom: none;
  }

  &:active {
    background: #f8f8f8;
  }

  .goods-goods {
    display: flex;
    align-items: flex-start;
    width: 100%;
    padding: 0;

    .delGoods {
      padding: 10upx;
      font-size: 30upx;
      color: #ff4757;
      border-radius: 50%;
      background: rgba(255, 71, 87, 0.08);
      margin-right: 10upx;
      transition: all 0.3s;

      &:active {
        background: rgba(255, 71, 87, 0.18);
        transform: scale(0.9);
      }
    }
  }

  .goods-img {
    width: 120upx;
    height: 120upx;
    background: #f5f5f5;
    border-radius: 10upx;
    margin-right: 18upx;
    border: 1upx solid #f0f0f0;
    overflow: hidden;

    image {
      width: 100%;
      height: 100%;
      border-radius: 8upx;
      object-fit: cover;
    }
  }

  .goods-cont-right {
    flex: 1;
    min-width: 0;

    .goods-tit {
      padding-bottom: 8upx;
      font-size: 28upx;
      color: #222;
      font-weight: 500;
      line-height: 1.4;
      word-break: break-all;
    }

    .goods-info {
      padding-bottom: 10upx;
      font-size: 24upx;
      color: #666;
      line-height: 1.5;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .gi-label {
        color: #888;
        margin-right: 2upx;
      }
      .gi-value {
        color: #333;
      }

      .buyNum-input {
        display: inline-block;
        width: 100upx;
        height: 48upx;
        line-height: 48upx;
        padding: 0 10upx;
        border: 1upx solid #e0e0e0;
        border-radius: 8upx;
        font-size: 24upx;
        vertical-align: middle;
        text-align: center;
        background: #f8f8f8;
        transition: all 0.3s;

        &:focus {
          border-color: #fb5904;
          background: #fff;
          box-shadow: 0 0 0 2upx rgba(251, 89, 4, 0.1);
        }
      }
    }
    .error-color {
      color: #fb5904;
      font-weight: 600;
      font-size: 26upx;
    }
  }
}

/* 添加商品按钮 */
.add-form-item {
  font-size: 28upx;
  padding: 24upx;
  background: #fff;
  margin: 18upx 0 0 0;
  border-radius: 12upx;
  box-shadow: 0 2upx 10upx rgba(0, 0, 0, 0.04);
  text-align: center;
  border: 2upx dashed #fb5904;
  transition: all 0.3s;

  &:active {
    transform: scale(0.98);
    background: rgba(251, 89, 4, 0.05);
  }

  .ibonxinzeng {
    font-size: 32upx;
    margin-right: 10upx;
    color: #fb5904;
  }
}

/* 底部提交按钮 */
.fixed-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 18upx 24upx 36upx;
  background: #fff;
  box-shadow: 0 -4upx 20upx rgba(0, 0, 0, 0.08);
  z-index: 999;

  .sub-btn {
    width: 100%;
    height: 80upx;
    line-height: 80upx;
    text-align: center;
    background: linear-gradient(135deg, #fb5904 0%, #ff7b3d 100%);
    color: #fff;
    border-radius: 10upx;
    font-size: 30upx;
    font-weight: 500;
    box-shadow: 0 6upx 20upx rgba(251, 89, 4, 0.18);
    transition: all 0.3s;

    &:active {
      transform: scale(0.98);
      box-shadow: 0 2upx 8upx rgba(251, 89, 4, 0.24);
    }
  }
}

/* 订单总额样式 */
.form-item.form-pa20 {
  background: #fff;
  border-radius: 10upx;
  margin: 18upx 0 0 0;
  font-size: 28upx;
  font-weight: 500;
  color: #222;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 18upx 24upx;
  box-shadow: 0 2upx 10upx rgba(0, 0, 0, 0.04);

  .icon-requird {
    color: #fb5904;
    margin-left: 4upx;
  }
}

/* 备注输入 */
.form-up {
  background: #fff;
  border-radius: 10upx;
  margin: 18upx 0 0 0;
  padding: 18upx 24upx;
  box-shadow: 0 2upx 10upx rgba(0, 0, 0, 0.04);

  .form-label {
    color: #333;
    font-size: 28upx;
    font-weight: 500;
    margin-bottom: 8upx;
  }
  .form-value input {
    width: 100%;
    border: none;
    background: transparent;
    font-size: 28upx;
    color: #222;
    padding: 0;
    outline: none;
  }
}

/* 空状态 */
.empty-goods {
  text-align: center;
  padding: 80upx 40upx;
  color: #999;

  .empty-icon {
    font-size: 100upx;
    color: #e0e0e0;
    margin-bottom: 20upx;
  }

  .empty-text {
    font-size: 28upx;
    color: #999;
    margin-bottom: 30upx;
  }

  .empty-btn {
    padding: 16upx 40upx;
    background: #fb5904;
    color: #fff;
    border-radius: 50upx;
    font-size: 26upx;
    transition: all 0.3s;

    &:active {
      transform: scale(0.95);
    }
  }
}
</style>
